import dayjs from "dayjs";
import { useCallback } from "react";
import { useSearchParams } from "react-router-dom";

export type StatsParamsT = {
  startDate?: string;
  endDate?: string;
  batchEndDate?: string;
};

export const useStatsParams = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const startDate = searchParams.get("startDate")
    ? (searchParams.get("startDate") as StatsParamsT["startDate"])
    : JSON.stringify(new Date("2023-01-01"));
  const endDate = searchParams.get("endDate")
    ? (searchParams.get("endDate") as StatsParamsT["endDate"])
    : JSON.stringify(new Date());
  const batchEndDate = searchParams.get("batchEndDate")
    ? (searchParams.get("batchEndDate") as StatsParamsT["batchEndDate"])
    : "%";

  const setStatsParams = useCallback((params: Partial<StatsParamsT>) => {
    setSearchParams((values: URLSearchParams) => {
      if (params.startDate !== undefined) {
        values.set("startDate", params.startDate);
      }
      if (params.endDate !== undefined) {
        values.set("endDate", params.endDate);
      }
      if (params.batchEndDate !== undefined) {
        values.set("batchEndDate", params.batchEndDate);
      }
      return values;
    });
  }, []);

  return {
    startDate,
    endDate,
    batchEndDate,
    setStatsParams,
  };
};
